package com.aididi.filters;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.servlet.filter.OrderedFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * 自定义全局过滤器，不需要在配置文件中配置，作用在所有的路由上
 * @Auther: zx.xu
 * @Description:    全局过滤器作用于所有的路由，不需要单独配置，
 * 我们可以用它来实现很多统一化处理的业务需求，比如权限认证，IP 访问限制等等。
 */
@Component
@Slf4j
public class AuthFilter implements GlobalFilter,OrderedFilter{


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        filterChain.doFilter(request,response);
    }

    /**
     * 鉴权过滤器
     * 校验请求中是否包含了请求参数token
     * 如何不包含请求参数“token”则不转发路由，否则执行正常的逻辑
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求参数token
        String queryParams = exchange.getRequest().getQueryParams().getFirst("token");
        if(queryParams ==null || queryParams.isEmpty()){
            log.info("token is empty..");
            ServerHttpResponse response = exchange.getResponse();
            // 封装错误信息
            Map<String, Object> responseData = Maps.newConcurrentMap();
            responseData.put("code", 401);
            responseData.put("message", "非法请求");
            responseData.put("cause", "Token is empty");

            // 将信息转换为 JSON
            try {
                ObjectMapper objectMapper = new ObjectMapper();
                byte[] bytes = new byte[0];
                bytes = objectMapper.writeValueAsBytes(responseData);
                // 输出错误信息到页面
                DataBuffer buffer = response.bufferFactory().wrap(bytes);
                //无权访问
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                response.getHeaders().add("Content-Type","application/json;charset=UTF-8");
                return response.writeWith(Mono.just(buffer));
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }


        }
        log.info("ending...");
        return chain.filter(exchange);
    }

    /**
     * 设置过滤器的执行顺序
     * @return
     */
    @Override
    public int getOrder() {
        return -999999999;
    }
}
